<template>
	<view class="category-container ">
		<!-- 搜索框区域 -->
		<SearchBar @search="onSearch" placeholder="搜索分类商品" :auto-navigate="false" />

		<view class="category-content">
			<!-- 左侧分类菜单 -->
			<view class="category-menu">
				<view class="menu-item" v-for="(category, index) in categoryList" :key="index"
					:class="{ active: activeIndex === index }" @click="selectCategory(index)">
					<text class="menu-text">{{ category.group_name }}</text>
				</view>
			</view>

			<!-- 右侧商品列表 -->
			<view class="product-content">
				<scroll-view scroll-y class="product-scroll">
					<!-- 分类横幅 -->
					<view class="category-banner" v-if="currentCategory.back_ground_image">
						<image :src="$tools.buildUrl(currentCategory.back_ground_image)" mode="aspectFill"
							class="banner-image"></image>
					</view>

					<!-- 商品网格 -->
					<view class="product-grid">
						<view class="product-item" v-for="(product, index) in searchResults" :key="index"
							@click="toProductDetail(product)">
							<image :src="$tools.buildUrl(product.white_back_ground_pic_url)" mode="aspectFill"
								class="product-image">
							</image>
							<view class="product-info">
								<text class="product-name">{{ product.spu_name }}</text>
								<text class="product-spec">已售：{{ product.sold_stock }}</text>
								<view class="product-price">
									<text class="price-symbol">¥</text>
									<text class="price-value">{{ product.price_min }}</text>
								</view>
							</view>
						</view>
					</view>
				</scroll-view>
			</view>
		</view>
	</view>
</template>

<script>
	import SearchBar from '@/components/SearchBar/SearchBar.vue'

	export default {
		components: {
			SearchBar
		},
		data() {
			return {
				categoryId: '',
				activeIndex: 0,
				searchKeyword: '',
				hasSearched: false,
				recordCount: 0,
				page: 1,
				limit: 10,
				categoryList: [],
				searchResults: [],
			}
		},
		computed: {
			currentCategory() {
				return this.categoryList[this.activeIndex] || {}
			}
		},
		onLoad(options) {
			// 如果有传入分类名称，自动选中对应分类
			if (options.id) {
				const index = this.categoryList.findIndex(item => item.id === options.id)
				if (index >= 0) {
					this.activeIndex = index
				}
			} else if (options.group_name) {
				const index = this.categoryList.findIndex(item => item.group_name === options.group_name)
				if (index >= 0) {
					this.activeIndex = index
				}
			}
			this.loadCategory()
		},

		onShow() {
			this.categoryId = uni.getStorageSync('tabCategoryId')
			uni.removeStorageSync('tabCategoryId') // 使用后删除
			if (this.categoryId) {
				const index = this.categoryList.findIndex(item => item.id === this.categoryId)
				if (index >= 0) {
					this.activeIndex = index
				}
			}
		},

		/**
		 * 页面相关事件处理函数--监听用户下拉动作
		 */
		onPullDownRefresh() {
			if (!this.hasSearched) {
				this.page = 1
				this.recordCount = 0
				this.searchResults = []
				this.loadDataList()
			}
		},

		/**
		 * 页面上拉触底事件的处理函数
		 */
		onReachBottom() {
			// 下拉触底，先判断是否有请求正在进行中
			// 以及检查当前请求页数是不是小于数据总页数，如符合条件，则发送请求
			const page = this.page
			const limit = this.limit
			const recordCount = this.recordCount
			if (!this.hasSearched && page * limit < recordCount) {
				this.page++
				setTimeout(() => {
					this.loadDataList()
				}, 500)
			}
		},
		methods: {
			// 搜索事件处理
			onSearch(searchQuery) {
				this.searchKeyword = searchQuery
				this.page = 1
				this.recordCount = 0
				this.searchResults = []
				this.loadDataList()
			},
			// 查询分类
			loadCategory() {
				this.$api.good.GetProductGroup({
					group_type: 1
				}).then(res => {
					this.categoryList = [{
						id: '',
						group_name: '全部',
						group_icon: '',
						back_ground_image: ''
					}]
					this.categoryList = this.categoryList.concat(res.data)
					const index = this.categoryList.findIndex(item => item.id === this.categoryId)
					if (index >= 0) {
						this.activeIndex = index
					}
					this.onSearch(this.searchKeyword)
				})
			},
			// 查询分类商品
			loadDataList() {
				if (this.hasSearched) {
					return false
				}

				this.hasSearched = true
				const group_id = this.activeIndex >= 0 ? this.categoryList[this.activeIndex].id : ''
				this.$api.good.GetProductList({
					page: this.page,
					limit: this.limit,
					group_id: group_id,
					keyword: this.searchKeyword
				}).then(res => {
					this.hasSearched = false
					this.recordCount = res.count
					this.searchResults = this.searchResults.concat(res.data)
				}).catch(err => {
					this.hasSearched = false
					if (this.page > 0) {
						this.page--
					}
				})
			},
			// 选择分类
			selectCategory(index) {
				this.activeIndex = index
				this.onSearch(this.searchKeyword)
			},
			// 跳转到商品详情
			toProductDetail(product) {
				uni.navigateTo({
					url: `/pages/product/detail?id=${product.id}`
				})
			},
			// 加入购物车
			addToCart(product) {
				uni.navigateTo({
					url: `/pages/product/detail?id=${product.id}`
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.category-container {
		background-color: #f8f8f8;
		height: 100vh;
		display: flex;
		flex-direction: column;
	}

	.header-right {
		display: flex;
		align-items: center;
	}

	.category-content {
		flex: 1;
		display: flex;
		overflow: hidden;
	}

	.category-menu {
		width: 200rpx;
		background-color: #ffffff;
		border-right: 2rpx solid #e5e5e5;
	}

	.menu-item {
		height: 100rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		border-bottom: 2rpx solid #f5f5f5;
		position: relative;
	}

	.menu-item.active {
		background-color: #f8f8f8;
	}

	.menu-item.active::before {
		content: '';
		position: absolute;
		left: 0;
		top: 50%;
		transform: translateY(-50%);
		width: 6rpx;
		height: 40rpx;
		background-color: #1c705e;
	}

	.menu-text {
		font-size: 28rpx;
		color: #333;
		text-align: center;
	}

	.menu-item.active .menu-text {
		color: #1c705e;
		font-weight: bold;
	}

	.product-content {
		flex: 1;
		width: calc(100% - 200rpx);
		background-color: #ffffff;
	}

	.product-scroll {
		height: 100%;
	}

	.category-banner {
		padding: 20rpx;
		overflow: hidden;
	}

	.banner-image {
		width: 100%;
		border-radius: 16rpx;
		height: 240rpx;
		object-fit: cover;
		object-position: top;
	}

	.product-grid {
		padding: 20rpx;
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
	}

	.product-item {
		width: 48%;
		background-color: #f9f9f9;
		border-radius: 16rpx;
		overflow: hidden;
		margin-bottom: 30rpx;
	}

	.product-image {
		width: 100%;
		height: 240rpx;
	}

	.product-info {
		padding: 20rpx;
	}

	.product-name {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 8rpx;
		display: block;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.product-spec {
		font-size: 22rpx;
		color: #999;
		margin-bottom: 12rpx;
		display: block;
	}

	.product-price {
		display: flex;
		align-items: baseline;
		margin-bottom: 20rpx;
	}

	.price-symbol {
		font-size: 24rpx;
		color: #1c705e;
	}

	.price-value {
		font-size: 32rpx;
		font-weight: bold;
		color: #1c705e;
	}

	.product-actions {
		display: flex;
		justify-content: center;
	}

	.add-cart-btn {
		background-color: #1c705e;
		color: #ffffff;
		border: none;
		border-radius: 8rpx;
		padding: 12rpx 24rpx;
		font-size: 24rpx;
	}
</style>